<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>My WebSocket</title>
</head>

<body>

UserId：<input id="userid">
<button onclick="connect()">Open</button>
<button onclick="closeWebSocket()">Close</button>

<br/>

消息：<input id="text" type="text"/>
<button onclick="send()">Send</button><br/>
To：<span id="to"></span>
<div id="list"></div>

<br/>

<div id="message">message:<br/></div>

</body>

<script type="text/javascript">
    var websocket = null;
    var target = "ws://localhost:8080/message/websocket/";

    function connect() {
        var userid = document.getElementById('userid').value;
        if (userid == '')
            target += '匿名';
        else
            target += userid;
        //判断当前浏览器是否支持WebSocket
        if ('MozWebSocket' in window) {
            websocket = new MozWebSocket(target);
        } else if ('WebSocket' in window) {
            websocket = new WebSocket(target);
        } else {
            alert('Not support websocket');
        }

        //连接成功建立的回调方法
        websocket.onopen = function (event) {
            setMessageInnerHTML("连接成功");
        }

        //连接发生错误的回调方法
        websocket.onerror = function () {
            setMessageInnerHTML("连接失败");
        };

        //接收到消息的回调方法
        websocket.onmessage = function (event) {
            var msg = event.data;
            if(msg.startsWith("users:")){
                aler
                setUsersList(msg.substring(6));
            }else{
                setMessageInnerHTML(msg);
            }
        }

        //连接关闭的回调方法
        websocket.onclose = function () {
            setMessageInnerHTML("连接关闭");
        }

    }

    //把用户显示在列表
    function setUsersList(userList){
        var users = userList.split(",");
        var html = "";
        for(var i=0;i<users.length;i++){
            html += "<a href='javascript:void(0)' onclick='toUser(this)'>"+users[i]+"</a><br/>";
        }
        document.getElementById('list').innerHTML = html;
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //关闭连接
    function closeWebSocket() {
        websocket.close();
    }

    function toUser(userid) {
        document.getElementById('to').innerText = userid.innerText;
    }

    //发送消息
    function send() {
        var message = document.getElementById('text').value;
        var to = document.getElementById('to').innerText;
        if (to != null && to != '') {
            websocket.send(message + '#' + to);
        } else {
            websocket.send(message);
        }
    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        websocket.close();
    }
</script>
</html>